/**
 * 本文件功能：公共JavaScript函数
 * 版权声明：保留发行权和署名权
 * 作者信息：功能反馈:15058593138@qq.com(手机号同微信)
 */

// AJAX通信函数
function ajax(url, data, callback, method = 'POST') {
    // 创建XMLHttpRequest对象
    var xhr = new XMLHttpRequest();
    
    // 准备请求
    xhr.open(method, url, true);
    
    if (method === 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    
    // 设置回调函数
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    var response = JSON.parse(xhr.responseText);
                    callback(response);
                } catch (e) {
                    console.error('解析响应失败:', e);
                    showToast('错误: 服务器返回的数据无法解析', 'error');
                }
            } else {
                console.error('请求失败:', xhr.status);
                showToast('错误: 请求失败', 'error');
            }
        }
    };
    
    // 发送请求
    var query = '';
    if (typeof data === 'object' && data !== null) {
        var params = [];
        for (var key in data) {
            if (data.hasOwnProperty(key)) {
                params.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
            }
        }
        query = params.join('&');
    } else if (typeof data === 'string') {
        query = data;
    }
    
    xhr.send(query);
}

// 获取表单数据函数
function getFormData(formId) {
    var form = document.getElementById(formId);
    if (!form) return {};
    
    var data = {};
    var elements = form.elements;
    
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        
        // 跳过按钮和未命名元素
        if (element.type === 'button' || element.type === 'submit' || element.type === 'reset' || !element.name) {
            continue;
        }
        
        // 根据元素类型获取值
        if (element.type === 'checkbox') {
            data[element.name] = element.checked ? '1' : '0';
        } else if (element.type === 'radio') {
            if (element.checked) {
                data[element.name] = element.value;
            }
        } else if (element.type === 'select-multiple') {
            var selectedOptions = [];
            for (var j = 0; j < element.options.length; j++) {
                if (element.options[j].selected) {
                    selectedOptions.push(element.options[j].value);
                }
            }
            data[element.name] = selectedOptions.join(',');
        } else {
            data[element.name] = element.value;
        }
    }
    
    return data;
}

// 表单验证函数
function validateForm(formId, rules) {
    var form = document.getElementById(formId);
    if (!form) return true;
    
    var elements = form.elements;
    var isValid = true;
    
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        
        // 跳过按钮和未命名元素
        if (element.type === 'button' || element.type === 'submit' || element.type === 'reset' || !element.name) {
            continue;
        }
        
        // 移除之前的错误提示
        removeValidationError(element);
        
        // 检查是否有验证规则
        if (rules && rules[element.name]) {
            var rule = rules[element.name];
            
            // 必填验证
            if (rule.required && element.value.trim() === '') {
                showValidationError(element, rule.message || '此项不能为空');
                isValid = false;
                continue;
            }
            
            // 最小长度验证
            if (rule.minLength && element.value.length < rule.minLength) {
                showValidationError(element, rule.message || '长度不能少于' + rule.minLength + '个字符');
                isValid = false;
                continue;
            }
            
            // 最大长度验证
            if (rule.maxLength && element.value.length > rule.maxLength) {
                showValidationError(element, rule.message || '长度不能超过' + rule.maxLength + '个字符');
                isValid = false;
                continue;
            }
            
            // 正则表达式验证
            if (rule.pattern && !rule.pattern.test(element.value)) {
                showValidationError(element, rule.message || '格式不正确');
                isValid = false;
                continue;
            }
            
            // 自定义验证函数
            if (rule.validator && typeof rule.validator === 'function') {
                var result = rule.validator(element.value);
                if (result !== true) {
                    showValidationError(element, result || '验证失败');
                    isValid = false;
                    continue;
                }
            }
        }
    }
    
    return isValid;
}

// 显示表单验证错误
function showValidationError(element, message) {
    // 创建错误提示元素
    var errorElement = document.createElement('div');
    errorElement.className = 'validation-error';
    errorElement.style.color = '#f44336';
    errorElement.style.fontSize = '12px';
    errorElement.style.marginTop = '5px';
    errorElement.textContent = message;
    
    // 设置输入框样式
    element.style.borderColor = '#f44336';
    
    // 插入错误提示元素
    element.parentNode.appendChild(errorElement);
}

// 移除表单验证错误
function removeValidationError(element) {
    // 重置输入框样式
    element.style.borderColor = '';
    
    // 查找并移除错误提示元素
    var parent = element.parentNode;
    var errorElements = parent.getElementsByClassName('validation-error');
    
    for (var i = errorElements.length - 1; i >= 0; i--) {
        parent.removeChild(errorElements[i]);
    }
}

// 显示遮罩层
function showModal(title, content, buttons) {
    // 创建遮罩层
    var overlay = document.createElement('div');
    overlay.className = 'overlay';
    overlay.id = 'modal-overlay';
    
    // 创建模态框
    var modal = document.createElement('div');
    modal.className = 'modal';
    modal.id = 'modal-container';
    
    // 创建模态框头部
    var modalHeader = document.createElement('div');
    modalHeader.className = 'modal-header';
    
    var modalTitle = document.createElement('div');
    modalTitle.className = 'modal-title';
    modalTitle.textContent = title;
    
    var closeButton = document.createElement('button');
    closeButton.className = 'modal-close';
    closeButton.innerHTML = '&times;';
    closeButton.onclick = hideModal;
    
    modalHeader.appendChild(modalTitle);
    modalHeader.appendChild(closeButton);
    
    // 创建模态框内容
    var modalBody = document.createElement('div');
    modalBody.className = 'modal-body';
    
    if (typeof content === 'string') {
        modalBody.innerHTML = content;
    } else if (content instanceof HTMLElement) {
        modalBody.appendChild(content);
    }
    
    // 创建模态框底部
    var modalFooter = document.createElement('div');
    modalFooter.className = 'modal-footer';
    
    if (Array.isArray(buttons)) {
        buttons.forEach(function(btn) {
            var button = document.createElement('button');
            button.className = 'btn ' + (btn.className || 'btn-primary');
            button.textContent = btn.text;
            button.onclick = btn.onClick || hideModal;
            modalFooter.appendChild(button);
        });
    } else {
        var defaultButton = document.createElement('button');
        defaultButton.className = 'btn btn-primary';
        defaultButton.textContent = '确定';
        defaultButton.onclick = hideModal;
        modalFooter.appendChild(defaultButton);
    }
    
    // 组装模态框
    modal.appendChild(modalHeader);
    modal.appendChild(modalBody);
    modal.appendChild(modalFooter);
    
    // 添加到文档
    overlay.appendChild(modal);
    document.body.appendChild(overlay);
    
    // 显示遮罩层
    overlay.style.display = 'block';
    
    // 确保模态框不超出屏幕
    if (modal.offsetHeight > window.innerHeight) {
        modal.style.height = (window.innerHeight * 0.9) + 'px';
        modalBody.style.overflow = 'auto';
    }
}

// 隐藏遮罩层
function hideModal() {
    var overlay = document.getElementById('modal-overlay');
    if (overlay) {
        document.body.removeChild(overlay);
    }
}

// 显示提示框
function showToast(message, type = 'success', duration = 3000) {
    // 移除已有提示框
    var existingToast = document.getElementById('toast');
    if (existingToast) {
        document.body.removeChild(existingToast);
    }
    
    // 创建提示框
    var toast = document.createElement('div');
    toast.id = 'toast';
    toast.className = 'toast toast-' + type;
    toast.textContent = message;
    
    // 添加到文档
    document.body.appendChild(toast);
    
    // 显示提示框
    toast.style.display = 'block';
    
    // 自动隐藏
    setTimeout(function() {
        toast.style.display = 'none';
        document.body.removeChild(toast);
    }, duration);
}

// 分页函数
function goPage(page, url) {
    window.location.href = url + (url.indexOf('?') > -1 ? '&' : '?') + 'page=' + page;
}

// 图片上传预览
function previewImage(input, previewContainer, maxCount = 5) {
    var files = input.files;
    var container = document.getElementById(previewContainer);
    
    // 清空预览容器
    container.innerHTML = '';
    
    // 创建文件数组，用于跟踪剩余的文件
    input.fileArray = Array.from(files).slice(0, maxCount);
    
    // 显示预览
    for (var i = 0; i < input.fileArray.length; i++) {
        var reader = new FileReader();
        
        reader.onload = (function(file, index) {
            return function(e) {
                var div = document.createElement('div');
                div.className = 'image-item';
                div.dataset.index = index;
                
                var img = document.createElement('img');
                img.src = e.target.result;
                
                var remove = document.createElement('span');
                remove.className = 'image-remove';
                remove.innerHTML = '&times;';
                remove.onclick = function() {
                    // 获取当前图片在数组中的索引
                    var curIndex = parseInt(div.dataset.index);
                    
                    // 从文件数组中移除
                    input.fileArray.splice(curIndex, 1);
                    
                    // 移除预览
                    div.remove();
                    
                    // 重新整理索引
                    var items = container.querySelectorAll('.image-item');
                    for (var j = 0; j < items.length; j++) {
                        items[j].dataset.index = j;
                    }
                    
                    // 如果没有图片了，清空文件输入框
                    if (input.fileArray.length === 0) {
                        input.value = '';
                        delete input.fileArray;
                    }
                };
                
                div.appendChild(img);
                div.appendChild(remove);
                container.appendChild(div);
            };
        })(input.fileArray[i], i);
        
        reader.readAsDataURL(input.fileArray[i]);
    }
}

// 图片上传处理
function uploadImages(input, callback, maxCount = 5) {
    // 使用fileArray（如果存在）而不是files
    var files = input.fileArray || input.files;
    if (!files || files.length === 0) {
        callback([]);
        return;
    }
    
    // 限制数量
    if (files.length > maxCount) {
        showToast('最多只能上传' + maxCount + '张图片', 'warning');
    }
    
    // 创建FormData对象
    var formData = new FormData();
    for (var i = 0; i < files.length && i < maxCount; i++) {
        formData.append('images[]', files[i]);
    }
    
    // 发送AJAX请求
    var xhr = new XMLHttpRequest();
    xhr.open('POST', 'inc/uimg.php', true);
    
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    var response = JSON.parse(xhr.responseText);
                    if (response.status === 'success') {
                        callback(response.data.uploaded);
                    } else {
                        showToast(response.msg, 'error');
                        callback([]);
                    }
                } catch (e) {
                    console.error('解析响应失败:', e);
                    showToast('错误: 服务器返回的数据无法解析', 'error');
                    callback([]);
                }
            } else {
                console.error('请求失败:', xhr.status);
                showToast('错误: 请求失败', 'error');
                callback([]);
            }
        }
    };
    
    xhr.send(formData);
}

// 压缩图片
function compressImage(file, maxWidth, callback) {
    var reader = new FileReader();
    reader.onload = function(e) {
        var img = new Image();
        img.onload = function() {
            var width = img.width;
            var height = img.height;
            
            if (width > maxWidth) {
                height = Math.round(height * maxWidth / width);
                width = maxWidth;
            }
            
            var canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;
            
            var ctx = canvas.getContext('2d');
            ctx.drawImage(img, 0, 0, width, height);
            
            canvas.toBlob(function(blob) {
                callback(blob);
            }, file.type, 0.8);
        };
        img.src = e.target.result;
    };
    reader.readAsDataURL(file);
}

// 批量压缩图片
function compressImages(files, maxWidth, callback) {
    var compressed = [];
    var count = 0;
    
    for (var i = 0; i < files.length; i++) {
        compressImage(files[i], maxWidth, function(blob) {
            compressed.push(blob);
            count++;
            
            if (count === files.length) {
                callback(compressed);
            }
        });
    }
}

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 绑定导航菜单点击事件
    var navItems = document.getElementsByClassName('nav-item');
    for (var i = 0; i < navItems.length; i++) {
        navItems[i].addEventListener('click', function() {
            var do_param = this.getAttribute('data-do');
            if (do_param) {
                window.location.href = window.location.pathname + '?do=' + do_param;
            }
        });
    }
    
    // 设置当前活动导航项
    var currentDo = getQueryParam('do');
    if (currentDo) {
        for (var i = 0; i < navItems.length; i++) {
            if (navItems[i].getAttribute('data-do') === currentDo) {
                navItems[i].classList.add('active');
            } else {
                navItems[i].classList.remove('active');
            }
        }
    }
});

// 获取URL查询参数
function getQueryParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
